const cors = require("cors");
const puppeteer = require("puppeteer-core");
const express = require("express");

const app = express();
const port = 3000;

// 使用 CORS 中间件，允许所有域的请求
app.use(cors());

// 创建一个全局浏览器实例以供重用
let browser;

async function getBrowserInstance() {
    if (browser == null) {
        browser = await puppeteer.launch({
            headless: 'new',
            args: ["--no-sandbox"],
            executablePath: "/usr/local/puppeteer/chrome-linux64/chrome",
        });
    }
    return browser;
}

app.get("/capture", async (req, res) => {
    try {
        const arg1 = decodeURIComponent(req.query.arg1);
        const arg2 = decodeURIComponent(req.query.arg2);

        if (!arg1) {
            return res.status(400).send("缺少 URL 参数。");
        }

        const browser = await getBrowserInstance();
        const page = await browser.newPage();

        await page.setViewport({width: 1920, height: 1080});
        await page.goto(arg1, {waitUntil: "networkidle2"});

        if (arg2) {
            await page.evaluate(arg2 => {
                window.location.hash = arg2;
            }, arg2);
            await page.waitForTimeout(3000);
        }

        const screenshot = await page.screenshot({fullPage: true});
        res.setHeader("Content-Type", "image/png");
        // 将 Buffer 转换为 base64 字符串
        const base64Screenshot = screenshot.toString("base64");

        res.status(200).json({
            status: 200,
            statusText: "OK",
            data: base64Screenshot,
        });

        await page.close(); // 关闭页面，释放资源
    } catch (error) {
        console.error("截图过程中出错:", error.stack);
        res.status(500).send("内部服务器错误");
    }
});

app.listen(port, () => {
    console.log(`服务器正在运行，访问地址：http://localhost:${port}`);
});

// 在服务器关闭时清理浏览器实例
process.on('exit', () => {
    if (browser !== null) {
        browser.close();
    }
});